package com.maltys.redission.config;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * 单机redis情况下的redisson配置
 *
 * @author malty
 */
@Slf4j
@Configuration
public class RedissonConfig {
    private static final String REDIS_CONFIG_PREFIX = "redis://";
    @Value("${spring.redis.host:null}")
    private String redisHost;
    @Value("${spring.redis.port:6379}")
    private Integer port;
    @Value("${spring.redis.password:null}")
    private String password;
    @Value("${spring.redis.sentinel.master:null}")
    private String masterNode;
    @Value("${spring.redis.sentinel.nodes:null}")
    private String sentinelNodes;

    @Bean
    @ConditionalOnProperty("spring.redis.host")
    public RedissonClient getRedissonSingle() {
        Config config = new Config();
        log.info("redisson 单节点配置");
        config.useSingleServer()
                .setPassword(password)
                .setAddress("redis://" + redisHost + ":" + port);
        config.setCodec(new JsonJacksonCodec());
        return Redisson.create(config);
    }

    @Bean
    @ConditionalOnProperty("spring.redis.sentinel.master")
    public RedissonClient getRedissonCluster() {
        Config config = new Config();
        log.info("redisson 集群配置");
        List<String> sentinels = StrUtil.split(sentinelNodes, ',');
        for (String sentinel : sentinels) {
            if (!sentinel.startsWith(REDIS_CONFIG_PREFIX)) {
                sentinel = REDIS_CONFIG_PREFIX + sentinel;
                config.useSentinelServers().addSentinelAddress(sentinel);
            }
        }
        config.useSentinelServers().setMasterName(masterNode);
        return Redisson.create(config);
    }
}
